<template>
  <div class="tableDome">
    <!-- 搜索栏 -->
    <div class="searchBox">
      <el-form
        ref="form"
        :model="searchFrom"
        label-width="80px"
        :class="searchBoxState ? 'searchFormZ' : 'searchFormS'"
      >
        <el-row id="searchBoxRowCols" class="searchBoxRow">
          <el-col :span="6">
            <el-form-item :label="translationData.address + '：'">
              <el-input
                v-model="searchFrom.address"
                size="small"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button
              v-if="searchBoxState"
              class="searchBtn"
              type="primary"
              size="small"
              icon="iconfont icon-search"
              :loading="searchLoading"
              @click="onSubmitSearch"
            >
              查询
            </el-button>
            <el-button
              v-if="searchBoxState"
              class="searchBtn"
              style="left: 170px"
              size="small"
              icon="iconfont icon-shanchu1"
              @click="emptySearchFrom"
            >
              清空
            </el-button>
          </el-col>
        </el-row>
      </el-form>
      <div
        v-if="searchBoxStateShow"
        :class="
          searchBoxState ? 'searchBoxStateBtbBox' : 'searchBoxStateBtbBoxZ'
        "
      >
        <el-button
          v-if="!searchBoxState"
          class="searchBtn"
          style="top: 0; left: 0"
          type="primary"
          size="small"
          icon="iconfont icon-search"
          :loading="searchLoading"
          @click="onSubmitSearch"
        >
          查询
        </el-button>
        <el-button
          v-if="!searchBoxState"
          class="searchBtn"
          style="top: 0; left: 90px"
          size="small"
          icon="iconfont icon-shanchu1"
          @click="emptySearchFrom"
        >
          清空
        </el-button>
        <el-button
          v-show="searchBoxState"
          size="small"
          class="searchStateBtn"
          type="text"
          icon="el-icon-arrow-up"
          @click="changeSearchBoxState(false)"
        >
          收起
        </el-button>
        <el-button
          v-show="!searchBoxState"
          size="small"
          class="searchStateBtn"
          type="text"
          icon="el-icon-arrow-down"
          @click="changeSearchBoxState(true)"
        >
          展开
        </el-button>
      </div>
    </div>
    <!-- 操作栏 -->
    <div class="actionBox">
      <!-- 新增按钮 -->
      <el-button
        class="addBtn"
        type="primary"
        size="small"
        icon="iconfont icon-add"
        @click="openAddDialog"
      >
        新增
      </el-button>
      <!-- 导出Excel按钮 -->
      <el-button
        class="exportBtn"
        size="small"
        icon="iconfont icon-daochu"
        :loading="downloadLoading"
        @click="exportExcel"
      >
        导出Excel
      </el-button>
      <!-- 上传Excel按钮 -->
      <el-upload
        ref="upload"
        class="uploadBtn"
        action="https:// jsonplaceholder.typicode.com/posts/"
        :multiple="false"
        :limit="1"
        :before-upload="beforeUpload"
        :on-success="onSuccess"
        :on-error="onError"
        :show-file-list="false"
      >
        <el-button
          size="small"
          icon="iconfont icon-daoru"
          :loading="uploadLoading"
        >
          上传Excel
        </el-button>
      </el-upload>
      <el-button
        :disabled="checkedsTable.length === 0"
        :class="
          checkedsTable.length !== 0 ? 'deletetBtn' : 'disabledDeletetBtn'
        "
        icon="iconfont icon-shanchu1"
        size="small"
        @click="batchDelete"
      >
        批量删除
      </el-button>
      <!-- 刷新按钮 -->
      <i class="refresh iconfont icon-shuaxin" @click="refresh" />
      <!-- 设置按钮 -->
      <el-popover width="100" trigger="click" popper-class="elPopover">
        <div class="popoverTitle">列展示</div>
        <el-checkbox-group
          v-model="checkeds"
          class="titlecheckboxGroup"
          @change="checkedsChange"
        >
          <el-checkbox
            v-for="(item, index) in tHeader"
            :key="index"
            :label="item"
          />
        </el-checkbox-group>
        <div class="popoverTitle hasTopLine">字体大小</div>
        <el-input-number
          v-model="tableFontSize"
          label="表格字体大小"
          size="mini"
          :min="12"
          :max="24"
          @change="changeTableFontSize"
        />
        <div class="popoverTitle hasTopLine">边框</div>
        <el-checkbox v-model="border" class="borderCheck">
          是否显示边框
        </el-checkbox>
        <i slot="reference" class="setUp iconfont icon-shezhi" />
      </el-popover>
    </div>
    <!-- 表格 -->
    <div class="tableBox">
      <el-table
        v-if="reload"
        v-loading="loading"
        element-loading-text="加载中"
        highlight-current-row
        :border="border"
        :data="tableData"
        :style="{
          width: '100%',
          fontSize: tableFontSize + 'px'
        }"
        @selection-change="selectionChange"
        @row-click="rowClick"
      >
        <el-table-column type="selection" />
        <el-table-column
          v-if="checkeds.toString().indexOf(translationData.date) !== -1"
          :label="translationData.date"
          prop="date"
          sortable
        >
          <!-- 行内编辑 -->
          <template slot-scope="scope">
            <div v-if="scope.row.editInTable" class="editInTable">
              <el-input
                v-model="scope.row.date"
                size="small"
                placeholder="请输入"
              />
              <el-button
                icon="iconfont icon-baocun"
                size="mini"
                type="success"
                :loading="editInTableUpLoading"
                @click="editInTableUp(scope.row)"
              >
                保存
              </el-button>
            </div>
            <div v-if="!scope.row.editInTable">
              {{ scope.row.date }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkeds.toString().indexOf(translationData.name) !== -1"
          :label="translationData.name"
          prop="name"
          sortable
        >
          <template slot-scope="scope">
            <div>
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkeds.toString().indexOf(translationData.address) !== -1"
          :label="translationData.address"
          prop="address"
          sortable
        >
          <template slot-scope="scope">
            <div>
              {{ scope.row.address }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="openEditDialog(scope.row)"
            >
              窗口编辑
            </el-button>
            <el-button
              v-if="!scope.row.editInTable"
              type="text"
              size="small"
              @click="openEditInTable(scope.row, true)"
            >
              行内编辑
            </el-button>
            <el-button
              v-if="scope.row.editInTable"
              type="text"
              size="small"
              @click="openEditInTable(scope.row, false)"
            >
              取消
            </el-button>
            <el-button
              type="text"
              size="small"
              class="tableDelBtn"
              @click="deletTableData(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="paginationBox">
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        :page-sizes="page.pageSizes"
        :page-size="page.pageSize"
        :current-page="page.currentPage"
        @size-change="pageSizeChange"
        @current-change="pageCurrentChange"
      />
    </div>
    <!-- 新增窗口 -->
    <el-dialog
      title="新增"
      :visible.sync="addDialog"
      width="40%"
      destroy-on-close
    >
      <Add @cancelAdd="cancelAdd" @confirmAdd="confirmAdd" />
    </el-dialog>
    <!-- 编辑窗口 -->
    <el-dialog title="编辑" :visible.sync="editDialog" width="40%">
      <Edit
        :data="editFrom"
        @cancelEdit="cancelEdit"
        @confirmEdit="confirmEdit"
      />
    </el-dialog>
  </div>
</template>

<script>
import translation from './translation.json'
import variables from '../../styles/table.scss'

export default {
  name: 'TableDemo',
  components: {
    Add: () => import('./add'),
    Edit: () => import('./edit')
  },
  props: {
    treeNodeRow: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      addDialog: false, //  新增窗口
      editDialog: false, //  编辑窗口
      searchBoxState: true, //  搜索栏默认展开
      searchBoxStateShow: true, // 搜索栏展开收起按钮是否展示
      reload: true, // 选择显示列的时候控制表格重新加载
      loading: false, //  表格加载
      downloadLoading: false, //  导出加载
      uploadLoading: false, //  上传加载
      searchLoading: false, //  查询加载
      editInTableUpLoading: false, //  行内编辑的查询加载
      border: false, //  默认表格无边框
      tableFontSize: variables.tableFontSize, //  表格默认字体大小
      tableData: [], //  表格数据
      editFrom: {}, //  编辑的列数据
      page: {
        total: 40,
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 20, 30, 40, 50]
      }, //  分页
      translationData: translation, //  翻译文件数据
      tHeader: [], //  表格字段翻译后的中文集合
      filterVal: [], //  表格真实字段集合
      checkeds: [], //  选择显示的列
      checkedsTable: [], //  表格多选列表
      searchFrom: {}, //  搜索的条件
      searchExcel: {} //  当搜索成功后searchFrom赋值于此,用于导出excel时
    }
  },
  watch: {
    treeNodeRow: {
      handler(newVal, oldVal) {
        if (newVal && Object.keys(newVal).length !== 0) {
          console.log('表格组件获取到树节点数据:', JSON.stringify(newVal))
          //  此处获取到树节点数据，把其中的查询条件放入searchFrom内
          this.searchFrom = {
            ...this.searchFrom,
            ...newVal
          }
          this.$nextTick(() => {
            this.getTableData()
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getTableData()
  },
  mounted() {
    this.showSearchBoxState()
  },
  methods: {
    //  获取tableData
    getTableData() {
      this.loading = true
      this.searchLoading = true
      //  查询条件 searchFrom
      //  分页数据 page
      //  根据这2个数据查询接口
      setTimeout(() => {
        let data = [
          {
            id: 1,
            treeId: 1,
            date: '2016-05-02',
            name: 'id:1',
            address: '上海市普陀区金沙江路 1517 弄'
          },
          {
            id: 2,
            treeId: 2,
            date: '2016-05-03',
            name: 'id:2',
            address: '上海市普陀区金沙江路 1518 弄'
          },
          {
            id: 3,
            treeId: 3,
            date: '2016-05-03',
            name: 'id:3',
            address: '上海市普陀区金沙江路 1518 弄'
          },
          {
            id: 4,
            treeId: 4,
            date: '2016-05-03',
            name: 'id:4',
            address: '上海市普陀区金沙江路 1518 弄'
          }
        ]
        //需要行内编辑则添加editInTable
        data.forEach((item) => {
          item.editInTable = false
        })
        this.tableData = data
        this.getTHeaderAndFilterVal()
        this.searchExcel = this.searchFrom
        this.loading = false
        this.searchLoading = false
      }, 1000)
    },

    //  查询
    onSubmitSearch() {
      console.log(this.searchFrom)
      this.getTableData()
    },

    //  清空
    emptySearchFrom() {
      this.searchFrom = {}
    },

    //  获取表格真实字段集合和中文集合
    getTHeaderAndFilterVal() {
      this.tHeader = []
      this.filterVal = []
      for (var i in this.tableData[0]) {
        if (this.translationData[i]) {
          this.tHeader.push(this.translationData[i])
          this.checkeds.push(this.translationData[i])
          this.filterVal.push(i)
        }
      }
    },

    //  选择分页大小
    pageSizeChange(val) {
      this.page.pageSize = val
      //  查询数据
      this.getTableData()
    },

    //  选择分页页码
    pageCurrentChange(val) {
      this.page.currentPage = val
      //  查询数据
      this.getTableData()
    },

    //  选择显示列
    checkedsChange(val) {
      this.checkeds = val
      this.$nextTick(() => {
        this.reload = false
        setTimeout(() => {
          this.reload = true
        }, 200)
      })
    },

    //  刷新
    refresh() {
      this.searchFrom = {}
      this.getTableData()
    },

    //  单个删除
    deletTableData(row) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log('需要删除的数据:', row)
        })
        .catch(() => {})
    },

    //  批量删除
    batchDelete() {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log('需要删除的数据:', this.checkedsTable)
        })
        .catch(() => {})
    },

    //  上传前判断是否为xlsx文件
    beforeUpload(file) {
      if (file.name.split('.')[file.name.split('.').length - 1] !== 'xlsx') {
        this.$message.warning('上传文件必须为excel文件！')
        return false
      } else {
        return true
      }
    },

    //  上传成功
    onSuccess(res, file) {
      this.$message.success('上传成功！')
      this.$refs.upload.clearFiles()
    },

    //  上传失败
    onError(err) {
      this.$message.error('上传失败！')
      console.log('上传失败', err)
    },

    //  导出Excel表格事件 从后端获取全部数据然后导出
    exportExcel() {
      this.downloadLoading = true
      //  根据searchExcel调取查询全部数据的接口
      setTimeout(() => {
        // 假设数据
        var fromData = [
          {
            date: '2016-05-02',
            name: '王小虎1',
            address: '上海市普陀区金沙江路 1518 弄'
          }
        ]
        import('../../vendor/Export2Excel').then((excel) => {
          const tHeader = this.tHeader
          const filterVal = this.filterVal
          const tableData = fromData
          const data = formatJson(filterVal, tableData)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'tableDemo'
            //  autoWidth: this.autoWidth,
            //  bookType: this.bookType
          })
          this.downloadLoading = false
        })
      }, 2000)

      function formatJson(filterVal, jsonData) {
        return jsonData.map((v) =>
          filterVal.map((j) => {
            return v[j]
          })
        )
      }
    },

    //  多选选择
    selectionChange(val) {
      this.checkedsTable = val
    },

    //  点击表格行
    rowClick(row) {
      this.$emit('changeNode', row)
    },

    // 搜索栏展开收起按钮是否展示
    showSearchBoxState() {
      if (
        document
          .getElementById('searchBoxRowCols')
          .getElementsByClassName('el-col-6').length > 4
      ) {
        this.searchBoxStateShow = true
      } else {
        this.searchBoxStateShow = false
      }
    },

    //  修改表格字体大小
    changeTableFontSize(val) {
      this.tableFontSize = val
    },

    //  切换搜索栏显示隐藏
    changeSearchBoxState(val) {
      this.searchBoxState = val
    },

    //  打开or取消行内编辑
    openEditInTable(row, val) {
      row.editInTable = val
      if (val === true) {
        this.tableData.forEach((item) => {
          if (item.id !== row.id) {
            item.editInTable = false
          }
        })
      }
    },

    //  行内编辑保存
    editInTableUp(row) {
      this.editInTableUpLoading = true
      setTimeout(() => {
        this.editInTableUpLoading = false
        this.getTableData()
      }, 1000)
    },

    //  打开新增窗口
    openAddDialog() {
      this.addDialog = true
    },

    //  取消新增
    cancelAdd() {
      this.addDialog = false
    },

    //  新增成功
    confirmAdd() {
      this.addDialog = false
      this.getTableData()
    },

    //  打开编辑窗口
    openEditDialog(row) {
      this.editFrom = row
      this.editDialog = true
    },

    //  取消编辑
    cancelEdit() {
      this.editDialog = false
    },

    //  编辑成功
    confirmEdit() {
      this.editDialog = false
      this.getTableData()
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/table.scss';

.tableDome {
  padding: 10px;
}
</style>
